package com.atguigu.spzx.manager.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.model.entity.product.Category;
import com.atguigu.spzx.model.vo.excel.ExcelCategoryVo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ExcelCategoryListener extends AnalysisEventListener<ExcelCategoryVo> {
    private List<Category> list = new ArrayList<>();
    private int limit = 100;
//    @Resource
//    CategoryMapper categoryMapper;
    CategoryMapper categoryMapper;

    public ExcelCategoryListener(CategoryMapper categoryMapper){
        this.categoryMapper = categoryMapper;
    }
    //每一行数据回调一次
    @Override
    public void invoke(ExcelCategoryVo data, AnalysisContext context) {
        //处理读取到的数据转为category对象,过滤掉已存在的数据
        Category category = convertExcelCategoryVo(data);
        if(category==null){//如果加载到的这行数据 在数据库中已存在 无需添加到list集合中
            return;
        }
        list.add(category);
        if(list.size()>=limit){
            //批量保存
            categoryMapper.saveBatch(list);
            //清除缓存
            list.clear();;
        }
    }
    //检查ExcelCategoryVo在数据库中是否已存在，不存在转为Category对象
    private Category convertExcelCategoryVo(ExcelCategoryVo data) {
        //id必须唯一 、  parentid+name组合 必须唯一
        long count = categoryMapper.countByIdOrPidName(data);
        if(count>0){
            //1、存在重复的数据  返回空
            return null;
        }
        //2、不存在 可以保存  转换为Category对象
        Category category = new Category();
        BeanUtils.copyProperties(data , category);
        category.setCreateTime(new Date());
        category.setUpdateTime(new Date());
        return category;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if(list.size()>0){
            //批量保存
            categoryMapper.saveBatch(list);
            //清除缓存
            list.clear();;
        }
    }
}
